﻿using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace Battle.Net.Infrastructure
{
    internal class TypeConverter<T>
        where T: class
    {
        internal T Convert(string json)
        {
            var serializer = new DataContractJsonSerializer(typeof (T));
            var bytes = Encoding.UTF8.GetBytes(json);
            var stream = new MemoryStream(bytes);
            var obj = (T)serializer.ReadObject(stream);
           // Validate(obj, json);

            return obj;
        }

        internal void Validate(T obj, string source)
        {
            var reader = JsonReaderWriterFactory.CreateJsonReader(Encoding.UTF8.GetBytes(source),
                                                                  new XmlDictionaryReaderQuotas());

            var root = XElement.Load(reader);
            var elements = new List<ValidationRecord>();
            foreach (var element in root.Descendants())
            {
                string key;
                string value;

                if (element.Parent.Name == "root")
                {

                    var record = new ValidationRecord
                        {
                            TypeName = obj.GetType().Name,
                            PropertyName = element.Name.ToString(),
                            PrimativeType = element.Attribute("type").ToString()
                        };

                    if (elements.All(e => e.PropertyName == record.PropertyName && e.TypeName == record.TypeName))
                        elements.Add(record);
                    
                    continue;
                }

                if (element.Parent.Name == "item")
                {
                      var record = new ValidationRecord
                        {
                            TypeName = element.Parent.Parent.Name.ToString(),
                            PropertyName = element.Name.ToString(),
                            PrimativeType = element.Attribute("type").ToString()
                        };


                    if (elements.All(e => e.PropertyName == record.PropertyName && e.TypeName == record.TypeName))
                        elements.Add(record);
                }

            }

            foreach (var e in elements)
            {
                Debug.Print(e.ToString());
            }

        }
    }

    internal class ValidationRecord
    {
        public string TypeName { get; set; }
        public string PropertyName { get; set; }
        public string PrimativeType { get; set; }

        public override string ToString()
        {
            return string.Format("{0}//{1} :: {2}", TypeName, PropertyName, PrimativeType);
        }
    }
}
